/**
 * Created by codedrinker on 2019/6/1.
 */

/**
 * 提交回复
 */
function post() {
    var questionId = $("#question_id").val();
    var content = $("#comment_content").val();
   // var converter = new showdown.Converter(); //初始化转换器
    //var content = converter.makeHtml($("#comment_content").val());
    //var htmlcontent = converter.makeHtml($("#comment_content").val()); //将MarkDown转为html格式的内容
    //console.log(htmlcontent);
    comment2target(questionId, 1, content);
}

//将评论的md文本转换成html代码显示
function markToHtml(id) {
    editormd.markdownToHTML('comment-view'+id, {});
};

function comment2target(targetId, type, content) {
    if (!content) {
        alert("不能回复空内容~~~");
        return;
    }

    $.ajax({
        type: "POST",
        url: "/comment",
        contentType: 'application/json',
        data: JSON.stringify({
            "parentId": targetId,
            "content": content,
            "type": type
        }),
        success: function (response) {
            if (response.code == 200) {
                window.location.reload();
            } else {
                if (response.code == 2003) {
                    var isAccepted = confirm(response.message);
                    if (isAccepted) {
                        window.open("/user/loginPage");
                        window.localStorage.setItem("closable", true);
                    }
                } else {
                    alert(response.message);
                }
            }
        },
        dataType: "json"
    });
}

//收藏
function followButton(e) {
    var questionId = e.getAttribute("data-id");
    var type;
    if ($("#FollowButton span").text() == "收藏") {
        type = 1;//关注
    } else {
        type = -1;//取关
    }

    $.ajax({
        type: "POST",
        url: "/questionLike",
        contentType: 'application/json',
        async: false, //同步请求
        data: JSON.stringify({
            "questionId": questionId,
            "type": type
        }),
        success: function (response) {
            if (response.code == 200) {
                if ($("#FollowButton span").text() == "收藏") {
                    $("#FollowButton").removeClass("Button--blue");
                    $("#FollowButton").addClass("Button--grey");
                    $("#FollowButton span").text("已收藏");
                } else {
                    $("#FollowButton").removeClass("Button--grey");
                    $("#FollowButton").addClass("Button--blue");
                    $("#FollowButton span").text("收藏");
                }
            } else {
                if (response.code == 2003) {
                    var isAccepted = confirm(response.message);
                    if (isAccepted) {
                        window.open("/user/loginPage");
                        window.localStorage.setItem("closable", true);
                    }
                } else {
                    var isAccepted = confirm(response.message);
                    if (isAccepted) {
                        window.location.reload();
                    }
                }
            }
        },
        dataType: "json"
    });
}

//点赞
function commentLike(e) {

    var commentId = e.getAttribute("data-id");
    var type;
    if (e.classList.contains("active")) {
        type = -1;//取消点赞
    } else {
        type = 1;//点赞
    }

    $.ajax({
        type: "POST",
        url: "/commentLike",
        contentType: 'application/json',
        async: false, //同步请求
        data: JSON.stringify({
            "commentId": commentId,
            "type": type
        }),
        success: function (response) {
            if (response.code == 200) {
                if (e.classList.contains("active")) {
                    e.classList.remove("active");
                } else {
                    e.classList.add("active");
                }
                var likeCount = $(e).find("span").eq(1).html();
                $(e).find("span").eq(1).html(parseInt(likeCount) + parseInt(type));
            } else {
                if (response.code == 2003) {
                    var isAccepted = confirm(response.message);
                    if (isAccepted) {
                        window.open("/user/loginPage");
                        window.localStorage.setItem("closable", true);
                    }
                } else {
                    var isAccepted = confirm(response.message);
                    if (isAccepted) {
                        window.location.reload();
                    }
                }
            }
        },
        dataType: "json"
    });
}

function comment(e) {
    var commentId = e.getAttribute("data-id");
    var content = $("#input-" + commentId).val();
    comment2target(commentId, 2, content);
}

/**
 * 展开二级评论
 */
function collapseComments(e) {
    var id = e.getAttribute("data-id");
    var comments = $("#comment-" + id);

    // 获取一下二级评论的展开状态
    var collapse = e.getAttribute("data-collapse");
    if (collapse) {
        // 折叠二级评论
        comments.removeClass("in");
        e.removeAttribute("data-collapse");
        e.classList.remove("active");
    } else {
        var subCommentContainer = $("#comment-" + id);
        if (subCommentContainer.children().length != 1) {
            //展开二级评论
            comments.addClass("in");
            // 标记二级评论展开状态
            e.setAttribute("data-collapse", "in");
            e.classList.add("active");
        } else {
            $.getJSON("/comment/" + id, function (data) {
                $.each(data.data.reverse(), function (index, comment) {
                    var mediaLeftElement = $("<div/>", {
                        "class": "media-left"
                    }).append($("<img/>", {
                        "class": "media-object img-rounded",
                        "src": '/image/'+comment.user.avatarUrl
                    }));

                    var mediaBodyElement = $("<div/>", {
                        "class": "media-body"
                    }).append($("<h5/>", {
                        "class": "media-heading",
                        "html": comment.user.name
                    })).append($("<div/>", {
                        "html": comment.content
                    })).append($("<div/>", {
                        "class": "menu"
                    }).append($("<span/>", {
                        "class": "pull-right",
                        "html": moment(comment.gmtCreate).format('YYYY-MM-DD')
                    })));

                    var mediaElement = $("<div/>", {
                        "class": "media"
                    }).append(mediaLeftElement).append(mediaBodyElement);

                    var commentElement = $("<div/>", {
                        "class": "col-lg-12 col-md-12 col-sm-12 col-xs-12 comments"
                    }).append(mediaElement);

                    subCommentContainer.prepend(commentElement);
                });
                //展开二级评论
                comments.addClass("in");
                // 标记二级评论展开状态
                e.setAttribute("data-collapse", "in");
                e.classList.add("active");
            });
        }
    }
}

function showSelectTag() {
    $("#select-tag").show();
}

function chooseCid(e) {
    var cidChoosed = e.getAttribute("data-id");
    //alert(cidChoosed);
    $("#cid").val(cidChoosed);
}

function generateHideElement(name, value) {
    var tempInput = document.createElement("input");
    tempInput.type = "hidden";
    tempInput.name = name;
    tempInput.value = value;
    return tempInput;
}

function selectTag(e) {
    var value = e.getAttribute("data-tag");
    var tabId = e.getAttribute("tag-id");
    var form = document.getElementById("public-form");
    var inputItem = generateHideElement("tags", tabId);
    form.appendChild(inputItem);
    var previous = $("#tag").val();
    if (previous.indexOf(value) == -1) {
        if (previous) {
            $("#tag").val(previous + ',' + value);
        } else {
            $("#tag").val(value);
        }
    }
}

//将绑定表单的昵称填写框显示或者隐藏
function showOrHiddenInputName(isHidden) {
    if (isHidden == 1){
        $("#inputName").hide();
        $("#secondPassword").hide();
    }
    else{
        $("#inputName").show();
        $("#secondPassword").show();
    }
}

//请求后台检测用户名是否存在
function checkUserIsExist(username) {
    var res;
    $.ajax({
        url: "/user/isExit/" + username,
        async: false,
        success: function (result) {
            res = result;
        }
    });
    return res == 1 ? true : false;
}

//请求后台检测用户名和密码是否匹配
function checkPassword(username, password) {
    var res;
    $.ajax({
        url: "/user/password/check",
        method: 'post',
        async: false,
        data: {
            username: username,
            password: password
        },
        success: function (result) {
            res = result;
        }
    });
    return res == 1 ? true : false;
}


//请求后台将用户与第三方用户进行绑定
function bindUser(username, accountId, htmlUrl, accountAvatar, accountName, witchGit) {
    $.ajax({
        url: "/user/bind",
        method: 'post',
        async: false,
        data: {
            username: username,
            accountId: accountId,
            htmlUrl: htmlUrl,
            accountAvatar: accountAvatar,
            accountName:accountName,
            witchGit: witchGit
        },
        success: function (result) {
            alert("绑定成功");
        }
    });
}

//请求后台用户登录
function userLogin(username, password) {
    var res;
    $.ajax({
        url: "/user/login",
        method: 'post',
        async: false,
        data: {
            username: username,
            password: password
        },
        success: function (result) {
            res = result;
        }
    });
    return res;
}

//请求后台注册用户
function userRegister(username, password, name) {
    var res;
    $.ajax({
        url: "/user/register",
        method: 'post',
        async: false,
        data: {
            username: username,
            password: password,
            name: name
        },
        success: function (result) {
            res = result;
        }
    });
    return res;
}

//用户登录的流程
function loginProcess() {
    var username = $("#inputUserName").val();
    var password = $("#inputPassword").val();
    var res = userLogin(username, password);
    if (res == 0)
        alert("用户名不存在！");
    else if (res == 1)
        alert("密码错误！");
    else
        document.location.href = "/";//登陆成功就跳转到首页
}

//用户注册的流程
function registerProcess() {
    var username = document.getElementById("inputUserName").value;
    var password = document.getElementById("inputPassword").value;
    var secondPassword=document.getElementById("secondPassword").value;
    if(!isSame(password,secondPassword))
        alert("两次密码输入不一致")
    else{
        var name = $("#inputName").val();
        if (userRegister(username, password, name) == 0)
            alert("用户名已存在！");
        else {
            alert("注册成功");
            document.location.href = "/user/loginPage";//注册成功就跳转到登陆页面
        }
    }
}

//将第三方用户和主用户进行绑定的流程
function bindProcess(accountId, htmlUrl, accountAvatar, accountName, witchGit) {
    var username = document.getElementById("bindInputUserName").value;
    var password = document.getElementById("bindInputPassword").value;
    if (document.getElementById("radioBindIsCreate").checked) {//如果选中的是绑定创建新用户
        var name = $("#inputName").val();
        var secondPassword=document.getElementById("secondPassword").value;
        if(!isSame(password,secondPassword))
            alert("两次密码输入不一致！");
        else{
            if (userRegister(username, password, name) == 0) //判断创建的用户名是否存在
                alert("用户名已存在！");
            else {
                bindUser(username, accountId, htmlUrl, accountAvatar, accountName, witchGit);//绑定用户
                if (userLogin(username, password) == 2)
                    document.location.href = "/";//登陆成功就跳转到首页
            }
        }
    } else {//如果选中的是绑定已有用户
        if (!checkUserIsExist(username)) //判断创建的用户名是否存在
            alert("该用户不存在！");
        else {
            if (!checkPassword(username, password)) //判断密码是否错误
                alert("密码错误！");
            else {
                bindUser(username, accountId, htmlUrl, accountAvatar, accountName, witchGit);//绑定用户
                if (userLogin(username, password) == 2)
                    document.location.href = "/";//登陆成功就跳转到首页
            }
        }
    }
}

//用于用户修改个人信息(文本类)之后的操作
function change(id, e) {
    var type = e.getAttribute("name");
    var newValue = e.value;
    if (confirm("是否确认修改？")) {
        if (updateMessage(id, type, newValue) == 1) {
            alert("修改成功");
            location.reload();
        } else{
            alert("修改失败,可能用户名已经存在");
            e.value = e.defaultValue;//失败时时还原
        }
    } else {
        e.value = e.defaultValue;//取消时还原
    }
}

//用于点击图片之后触发文件选择
function fileSelect() {
    document.getElementById("fileToUpload").click();
}

//用于上传图片修改头像
function fileSelected(id) {
    // 文件选择后触发次函数
    var $file1 = $("input[id='fileToUpload']").val();//用户文件内容(文件)
    // 判断文件是否为空
    if ($file1 == "") {
        alert("请选择上传的目标文件! ")
        return false;
    }
    //判断文件类型,我这里根据业务需求判断的是图片文件
    var fileName1 = $file1.substring($file1.lastIndexOf(".") + 1).toLowerCase();
    if (fileName1 != "jpg" && fileName1 != "png" && fileName1 != "jpeg" && fileName1 != "jpeg" && fileName1 != "gif" && fileName1 != "bmp" && fileName1 != "webp") {
        alert("请选择图片文件!");
        return false;
    }
    //判断文件大小
    var size1 = $("input[id='fileToUpload']")[0].files[0].size;
    if (size1 > 209715200) {
        alert("上传文件不能大于20M!");
        return false;
    }
    var formData = new FormData();//这里需要实例化一个FormData来进行文件上传
    formData.append("file", $("#fileToUpload")[0].files[0]);
    $.ajax({
        type: "post",
        url: "/image/upload",
        data: formData,
        processData: false,
        contentType: false,
        success: function (data) {
            if (updateMessage(id, 'avatar', data) == 1) {
                alert("修改成功");
                location.reload();
            }
        }
    });
}

//用于向后台请求去修改个人信息
function updateMessage(id, type, newValue) {
    var res = 0;
    $.ajax({
        url: "/user/",
        method: 'put',
        async: false,
        data: {
            id: id,
            type: type,
            newValue: newValue
        },
        success: function (result) {
            res = result;
        }
    });
    return res;
}

//用于比较输入的两次密码是否一致
function isSame(x,y) {
    return x==y;
}
//用于向后台请求修改密码
function updatePassword(username) {
    var oldPassword=document.getElementById("oldPassword").value;
    var firstNewPassword=document.getElementById("firstNewPassword").value;
    var secondNewPassword=document.getElementById("secondNewPassword").value;
    if(!isSame(firstNewPassword,secondNewPassword)){
        alert("两次密码输入不一致");
        return;
    }
    $.ajax({
        url: "/user/psw",
        method: 'put',
        async: false,
        data: {
            username:username,
            oldPassword:oldPassword,
            newPassword:secondNewPassword
        },
        success: function (result) {
            if(result==0)
                alert("原密码不正确！");
            else
                alert("修改成功");
        }
    });
}

//用于向后台请求解绑用户
function unbind(id,witchGit) {
    if (confirm("是否确认解绑？")) {
        $.ajax({
            url: "/user/unbind",
            method: 'put',
            async: false,
            data: {
                id:id,
                witchGit:witchGit
            },
            success: function (result) {
                alert("解绑成功");
                location.reload();
            }
        });
    }
}

function deleteButton(e) {
    var questionId=e.getAttribute("data-id");
    if (confirm("是否确认要删除此问题？")) {
        $.ajax({
            url: "/question/"+questionId,
            method: 'delete',
            async: false,
            success: function (result) {
                if(result==1){
                    alert("删除成功");
                    document.location.href = "/";//登陆成功就跳转到首页
                }
            }
        });
    }
}

function onclick_go(){
    $('body,html').animate({scrollTop: $('#comment_position').offset().top}, 500);
}